import { createSelectorQuery } from '@tarojs/taro';

export const getScrollBottom = function (name: string) {
    return new Promise<number>(() => {
        const query = createSelectorQuery();
        query.select(name).boundingClientRect();
        query.selectViewport().scrollOffset();
        query.exec((res) => {
            console.log(res);
        });
    });
};
const MIN_DISTANCE = 10;
export function getDirection(x: number, y: number) {
    if (x > y && x > MIN_DISTANCE) {
        return 'horizontal';
    }
    if (y > x && y > MIN_DISTANCE) {
        return 'vertical';
    }
    return '';
}

export function rubberband(distance: number, stiffness = 0.5, maxDistance = Infinity): number {
    // 确保stiffness在有效范围内
    let newStiffness = stiffness;
    newStiffness = Math.max(0.01, Math.min(0.99, stiffness));

    // 限制最大距离
    const boundedDistance = Math.min(Math.abs(distance), maxDistance);

    // 使用三次方曲线创建平滑弹性效果
    // 这种曲线在起始点有零导数，确保平滑过渡
    const normalizedDistance = boundedDistance / maxDistance;
    const elasticRatio = normalizedDistance * normalizedDistance * (3 - 2 * normalizedDistance);

    return maxDistance * elasticRatio * newStiffness;
}
/**
 * 优化的边界弹性处理函数，确保在边界附近有平滑过渡
 * @param position - 当前位置
 * @param min - 最小边界
 * @param max - 最大边界
 * @param stiffness - 弹性刚度，值越小弹性越大
 * @param transitionZone - 边界过渡区域大小(px)
 * @param maxDistance - 最大弹性距离(px)
 * @returns 应用弹性效果后的位置
 */
export function rubberbandIfOutOfBounds(
    position: number,
    min: number,
    max: number,
    stiffness = 0.5,
    transitionZone = 50,
    maxDistance = 300
): number {
    // 在边界内直接返回原始位置
    if (position >= min && position <= max) {
        return position;
    }

    // 计算超出边界的距离
    const overshoot = position < min ? min - position : position - max;

    // 边界附近的过渡区域处理
    if (overshoot <= transitionZone) {
        // 在过渡区域内，使用线性插值平滑过渡到完整弹性效果
        const progress = overshoot / transitionZone;
        const linearAdjustment = overshoot * progress;

        return position < min ? min - linearAdjustment : max + linearAdjustment;
    }

    // 超出过渡区域，应用完整弹性效果
    const rubberbandDistance = rubberband(
        overshoot - transitionZone,
        stiffness,
        maxDistance - transitionZone
    );

    return position < min
        ? min - transitionZone - rubberbandDistance
        : max + transitionZone + rubberbandDistance;
}
export const sleep = (time: number): Promise<unknown> =>
    new Promise((resolve) => setTimeout(resolve, time));
